package org.swxjava.assembler.avm1;

import org.swxjava.assembler.Constants;
import org.swxjava.assembler.ObjectCompiler;
import org.swxjava.util.ArrayUtils;
import org.swxjava.util.Log;
import org.swxjava.util.LogFactory;
import org.swxjava.util.StringUtils;

public class AsDouble implements ObjectCompiler {

	/** Logger */
	private static final Log LOG = LogFactory.getLog(AsDouble.class);

	/** value */
	private Double value = 0.0;

	public AsDouble(Double value) {
		this.value = value;
	}

	public int getByteSize() {
		return toString().length() / 2;
	}

	public byte[] toBytecode() {
		// TODO Auto-generated method stub
		return null;
	}

	public String toString() {
		return doubleToBytecode(value);
	}

	public static String doubleToBytecode(double d) {
		if (Double.isNaN(d)) {
			return Constants.NUMBER_NAN;
		}
		String b = Long.toHexString(Double.doubleToRawLongBits(d))
				.toUpperCase();
		String[] dbytes = StringUtils.split(b, 2);

		ArrayUtils.reverse(dbytes);

		StringBuffer hex = new StringBuffer();
		for (int i = 4; i < 8; i++) {
			hex.append(dbytes[i]);
		}
		for (int i = 0; i < 4; i++) {
			hex.append(dbytes[i]);
		}
		String bytecode = Constants.DATA_TYPE_DOUBLE + hex.toString();
		if (LOG.isDebugEnabled()) {
			LOG.debug(d + " : " + bytecode);
		}
		return bytecode;
	}
}
